package br.org.universa.sgos.web;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import br.org.universa.sgos.enums.OperacaoEnum;
import br.org.universa.sgos.web.operacao.Operacao;

@WebServlet(urlPatterns = "/executa")
public class WebController extends HttpServlet {

	private static final Logger logger = Logger.getLogger(WebController.class);

    private static final long serialVersionUID = 1L;

    @Override
    protected void service(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {

        String nomeClasseOperacao = request.getParameter("operacao");

        if (StringUtils.isEmpty(nomeClasseOperacao)) {
            throw new IllegalArgumentException("Operacao não informada.");
        }

        try {

            Operacao instancia = instanciaOperacao(nomeClasseOperacao);
            String paginaRedirecionamento = instancia.executa(request, response);
            request.getRequestDispatcher(paginaRedirecionamento).forward(request, response);

        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
        }

    }

	private Operacao instanciaOperacao(String nomeClasseOperacao)
			throws InstantiationException, IllegalAccessException,
			ClassNotFoundException {

    	for (OperacaoEnum operacaoEnum : OperacaoEnum.values()) {
    		if (operacaoEnum.getOperacao().endsWith(nomeClasseOperacao)) {

    			String fqnOperacao = operacaoEnum.fqnOperacao();

    			logger.info("Criando uma instancia de " + fqnOperacao);

				return (Operacao) Class.forName(fqnOperacao).newInstance();
    		}
		}

    	return null;
    }
}
